//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import recordItem from '../comm/recordItem.vue'
import BScroll from 'better-scroll';
import timeSelectPop from '../comm/timeSelectPop.vue'
import { Image as VanImage } from "vant";
import { scrollMixin } from "utils/mixin";
export default {
  name:'',
  mixins: [scrollMixin], //加载更多
  //import引入的组件需要注入到对象中才能使用
  components: {
    VanImage,
    recordItem,
    timeSelectPop
  },
  data() {
  return {
    active:0,
    id:'',
    query:{
      admin_type:0,
      activity_id:'',
      page:1,
      search:{
        time:[]
      }
    },
    checkQuery:{
      check_type:'',
      id:''
    },
    totalPage:0,
    isLoadMore:true,
    //获取自己的打卡记录
    clockList:[],
    memberTab:[
      {
        name:'活动详情',
        value:0,
      },
      {
        name:'打卡记录',
        value:1,
      }
    ],
    status:1,
    timeShow:false, //时间查询
    dateShow:false,
    awardShow:false,
    iPnoneBottomBol: false, //是否是苹果手机
    timeIndex:0,
    timeList:[
      {
        name:'全部',
        value:0,
      },
      {
        name:'最近3天',
        value:1,
      },
      {
        name:'今天',
        value:2,
      },
      {
        name:'昨天',
        value:3,
      },
      {
        name:'上周',
        value:4,
      },
      {
        name:'本周',
        value:5,
      },
      {
        name:'上月',
        value:6,
      },
      {
        name:'本月',
        value:7,
      }
    ],
    awardList:[],
    recordData:[],
    info:{},
    clockStatus:'',
    taskShow:false,
    partInfo:{},
    total:'',
    
    //是否是管理员
    isAdmin:false,
    memberInfo:{},
    coThemeColor:'',
    //获取当前这周的日期
    weekArr:[],
    //奖励记录的参数
    awardQuery: {
      page:1,
      activity_id:''
    },
    awardTotal:0,
    awardMore:true,
    debounce_timer:null,
    awardScroll:'',
    timeName:'全部时间',
    pluginId:'',
    imgPath:''
  };
  },
  //监听属性 类似于data概念
  computed: {
    percentage() {
      let percentNum = 0;
      //连续打卡的情况
      if(this.info.is_continuous == 1) {
        percentNum = this.partInfo.continuous_day /  this.info.count_day ;
      } else {
        percentNum = this.partInfo.sum_day /  this.info.count_day;
      }
       
      let result  = (Math.round(percentNum * 10000) / 10000) * 100;
      return result;
    }
  },
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    clockOn(status) {
      if(status == 0) {
        this.$router.push(this.fun.getUrl("goods", { id: this.info.goods_id }));
      } else {
      }
    },
    debounce() {
      // clearTimeout方法，以便控制连续触发带来的无用调用
      if (this.debounce_timer) {
        clearTimeout(this.debounce_timer); // 先清除之前的延时，并在下面重新开始计算时间
      }
      this.debounce_timer = setTimeout(() => {
        // 800毫秒以后执行方法
        this._initScrollList();
      }, 200); // 如果还没有执行就又被触发，会根据上面的clearTimeout来清除并重新开始计算
    },
    awardOpen() {
      this.$nextTick(() => {
        this.awardShow = true;
        if(this.awardList.length > 0) {
          this.debounce();
        }
        // setTimeout(() => {
        //   if(this.awardList.length > 0) {
        //     this.awardScroll.refresh();
        //   }
        // },200)
      });
    },
    colorFin(a) { //处理主题色
      a = a.substring(1);
      a = a.toLowerCase();
      let b = new Array();
      for (let x = 0; x < 3; x++) {
        b[0] = a.substr(x * 2, 2);
        b[3] = "0123456789abcdef";
        b[1] = b[0].substr(0, 1);
        b[2] = b[0].substr(1, 1);
        b[20 + x] = b[3].indexOf(b[1]) * 16 + b[3].indexOf(b[2]);
      }
      return b[20] + "," + b[21] + "," + b[22];
    },
    ispartOn() {
      if(this.partInfo.is_participate == 1) {
        this.$router.push(this.fun.getUrl("clockAdd", {},{ id:this.id,pluginId:this.pluginId,goodsId:this.partInfo.goods_id,orderId: this.partInfo.order_id}));
      } else {
        this.partCheck();
      }
    },
    punchTo() {
      // this.$router.push(this.fun.getUrl("clockCalendar",{},{id:this.query.id}));
      this.$router.push(this.fun.getUrl("clockMember",{}));
    },
    calendarTo() {
      this.$router.push(this.fun.getUrl("clockCalendar",{},{id:this.id}));
    },
    //跳转售后
    refundOn() {
      this.$router.push(
        this.fun.getUrl(
          "refund",
          {
            order_id: this.partInfo.order_id,
            order_type: this.pluginId,
          },
          {orderType:'rebate',partId:this.id,goodsId:this.partInfo.goods_id}
        )
      );
    },
    closeTask() {
      this.taskShow = false;
    },
    //获取当前一周的日期
    getWeekDates() {  
        const today = new Date();  
        const dayOfWeek = today.getDay(); // 获取今天是星期几（0-6，0表示周日）
        const todayDate = today.getDate();
        // 计算本周一的日期  
        let startOfWeek = new Date(today);  
        startOfWeek.setDate(today.getDate() - dayOfWeek + (dayOfWeek === 0 ? -6 : 1));  
      
        // 计算本周日的日期  
        let endOfWeek = new Date(startOfWeek);  
        endOfWeek.setDate(startOfWeek.getDate() + 6);  
      
        // 获取当前一周的每一天日期  
        const weekDates = [];
       
        for (let i = 0; i < 7; i++) {  
            const date = new Date(startOfWeek);  
            date.setDate(startOfWeek.getDate() + i); 
            const formattedDate = date.getDate();
            weekDates.push({
              date:formattedDate,
              dataName:formattedDate,
              check_in_type:0
            });  
        }  
        return weekDates;
    },
    //打卡记录的修改
    recordPost(item,status) {
      let recordQuery = {
        id:item.id
      }
      let message = '';
      if(status == 'hide') {
        item.is_hide==1?message ='取消隐藏打卡记录?':message ='确认隐藏打卡记录?';
        this.$dialog.confirm({
          title: '提示',
          message:message,
        })
        .then(() => {
          // on confirm
          item.is_hide == 0?recordQuery.is_hide=1:recordQuery.is_hide=0;
          recordQuery.check_type = 1;
          this.checkInLogData(recordQuery);
        })
        .catch(() => {
          // on cancel
        });
        
      }
      if(status == 'top') {
        item.is_top==1?message ='取消置顶打卡记录?':message ='确认置顶打卡记录?';
        this.$dialog.confirm({
          title: '提示',
          message:message,
        })
        .then(() => {
          // on confirm
          recordQuery.check_type = 2;
          item.is_top == 0?recordQuery.is_top=1:recordQuery.is_top=0;
          this.checkInLogData(recordQuery);
        })
        .catch(() => {
          // on cancel
        });
      }
      
    },
    checkInLogData(recordQuery) {
      $http.post("plugin.check-in-rebate.frontend.participate-in.change-check-in-log", recordQuery, "正在获取").then(
        response => {
          if (response.result == 1) {
            let res = response.data;
            this.$toast(response.msg);
            this.query.page = 1;
            this.recordData = [];
            this.recordListData();
          } else {
            
            this.$dialog.alert({ message: response.msg });
          }
        },
        function(response) {
          // console.log(response);
          // error callback
        }
      );
    },
    //打卡活动记录参加打卡接口
    partCheck() {
      $http.get("plugin.check-in-rebate.frontend.participate-in.participate-in", {id:this.id}, "正在获取").then(
        response => {
          let res = response.data;
          if (response.result == 1) {
            this.$toast(response.msg);
            this.getMember();
            this.taskShow = true;
          } else {
            this.$dialog.confirm({
              title: '提示',
              message: '商品订单确认收货后才可以打卡',
            })
            .then(() => {
              // on confirm
              if(res.type == 'no_receive') {
                this.$router.push(this.fun.getUrl("orderlist", { status: "3" ,orderType:"shop"}));
              }
            })
            .catch(() => {
              // on cancel
            });
            // this.$dialog.alert({ message: response.msg });
          }
        },
        function(response) {
          // console.log(response);
          // error callback
        }
      );
    },
    //未购买商品的商品详情
    getDetail() {
      $http.get("plugin.check-in-rebate.frontend.index.getDetail", {id:this.query.activity_id}, "正在获取").then(
        response => {
          if (response.result == 1) {
            let res = response.data;
            this.info = res;
            this.awardQuery.activity_id = res.id;
            this.awardData();
          } else {
            
            this.$dialog.alert({ message: response.msg });
          }
        },
        function(response) {
          // console.log(response);
          // error callback
        }
      );
    },
    //购买商品的商品详情
    getMember() {
      $http.get("plugin.check-in-rebate.frontend.participate-in.get-detail", {id:this.id}, "正在获取").then(
        response => {
          let res = response.data;
          console.log(res);
          if (response.result == 1) {
            this.info = res.activity;
            this.partInfo = res;
            //打卡领取奖励
            this.awardQuery.activity_id = res.activity_id;
            this.awardData();
           
          } else {
            //分享有打卡的活动详情，不同的mid会导致会员显示的打卡信息错误，跳转到未参与的活动详情
            if(res.activity_id) {
              this.$router.replace(this.fun.getUrl("clockDetails", {},{activityId:res.activity_id,clockStatus:0}));
            } else {
              this.$dialog.alert({ message: response.msg });
            }
            
          }
        },
        function(response) {
          // console.log(response);
          // error callback
        }
      );
    },
    getMemberInfo() {
      $http.get("plugin.check-in-rebate.frontend.participate-in.get-Info", {}, "正在获取").then(
        response => {
          if (response.result == 1) {
            let res = response.data; 
            if(res.member.is_admin) {
              this.query.admin_type = 1;
              this.isAdmin = true;
            }
            this.isAdmin = res.member.is_admin;
            this.memberInfo = res.member;
            this.recordListData();
          } else {
            
            this.$dialog.alert({ message: response.msg });
          }
        },
        function(response) {
          // console.log(response);
          // error callback
        }
      );
    },
    _initScrollList() {
      if (this.awardList.length > 0) {
        this.awardScroll = new BScroll(this.$refs.handpickList, {
          click: true,
          scrollY: true,
          probeType: 3,
          swipeBounceTime: 500,
          useTransition: false,
          mouseWheel: true
        });
      } else {
        this.awardScroll.refresh();
      }
      let loadMore = document.getElementById("awardMore");
      this.awardScroll.on("scroll", pos => {
        if (loadMore?.offsetTop > this.$refs.handpickList?.offsetHeight && loadMore?.offsetTop + pos.y < this.$refs?.handpickList.offsetHeight && this.isLoadMore) {
          this.awardMoreData();
          setTimeout(() => {
            this.awardScroll.refresh();
          }, 800);
        }
      });
      this.$once("hook:beforeDestroy", () => {
        window.removeEventListener("scroll", this.awardScroll);
      });
    },
    //奖励记录
    awardData() {
      $http.post("plugin.check-in-rebate.frontend.participate-in.rewards",this.awardQuery, "正在获取").then(
        response => {
          if (response.result == 1) {
            let res = response.data;
            this.awardMore = true;
            this.awardTotal = res.last_page;
            if (!this.awardTotal) {
              this.awardQuery.page = 0;
            }
            this.awardList = res.data;
           
          } else {
            this.awardQuery.page = this.awardQuery.page - 1;
            this.awardMore = false;
            // this.$dialog.alert({ message: response.msg });
          }
        },
        function(response) {
          // console.log(response);
          // error callback
        }
      );
    },
    awardMoreData() {
      this.awardMore = false; // 防止多次请求分页数据
      if (this.awardQuery.page >= this.awardTotal) {
        return;
      } else {
        this.awardQuery.page  = this.awardQuery.page+1;
        $http.get("plugin.check-in-rebate.frontend.participate-in.rewards", this.awardQuery, "正在获取").then(
          response => {
            if (response.result == 1) {
              let res = response.data;
              let list = res.data;
              this.awardMore = true;
              this.awardList = [...this.awardList, ...list];
            } else {
              this.awardQuery.page = this.awardQuery.page - 1;
              this.awardMore = false;
              this.$dialog.alert({ message: response.msg });
            }
          },
          function(response) {
            // console.log(response);
            // error callback
          }
        );
      }
    },
    //自己的打卡记录
    clockListData() {
      // admin_type:1,是管理员状态（可以查看所有的打卡记录），但是只能自己看自己的打卡记录，所以    写死状态
      let query = {
        admin_type:1,
        id:this.id,
        page_type:1
      }
      $http.post("plugin.check-in-rebate.frontend.participate-in.check-in-log",query, "正在获取").then(
        response => {
          if (response.result == 1) {
            let res = response.data;
            this.clockList = res;
            this.weekArr = this.getWeekDates() || [];

             //今天的日期
            let now = new Date();
            let toMonth = now.getMonth() + 1;
            let toDay = now.getDate();
            this.weekArr.map((item,index) => {
              if(toDay ==  item.date) {
                item.dataName = '今';
              }
              this.clockList.map((clockItem,clockIndex) => {
                let time =  new Date(clockItem.created_at);
                let recordMonth = time.getMonth() + 1;
                if(time.getDate() == item.date  && toMonth == recordMonth) {
                  item.check_in_type = clockItem.check_in_type
                }
                
              })
            })
            
            console.log(this.weekArr);
            // this.weekArr();
          } else {
            this.$dialog.alert({ message: response.msg });
          }
        },
        function(response) {
          // console.log(response);
          // error callback
        }
      );
    },
    //公共的打卡记录
    recordListData() {
      $http.post("plugin.check-in-rebate.frontend.participate-in.check-in-log",this.query, "正在获取").then(
        response => {
          if (response.result == 1) {
            let res = response.data;
            this.isLoadMore = true;
            this.totalPage = res.last_page;
            if (!this.totalPage) {
              this.query.page = 0;
            }
            this.recordData = res.data;
            this.total = res.total;
          } else {
            this.query.page = this.query.page - 1;
            this.isLoadMore = false;
            // this.$dialog.alert({ message: response.msg });
          }
        },
        function(response) {
          // console.log(response);
          // error callback
        }
      );
    },
   
    getMoreData() {
      this.isLoadMore = false; // 防止多次请求分页数据
      if (this.query.page >= this.totalPage) {
        return;
      } else {
        this.query.page  = this.query.page+1;
        $http.post("plugin.check-in-rebate.frontend.participate-in.check-in-log", this.query, "正在获取").then(
          response => {
            if (response.result == 1) {
              let res = response.data;
              let list = res.data;
              this.isLoadMore = true;
              this.recordData = [...this.recordData, ...list];
            } else {
              this.query.page = this.query.page - 1;
              this.isLoadMore = false;
              this.$dialog.alert({ message: response.msg });
            }
          },
          function(response) {
            // console.log(response);
            // error callback
          }
        );
      }
    },
    timeSelect(data) {
      let {item,index} = data;
      this.timeIndex = index;
    },
    timeConfirm(data) {
      let {result,timeName} = data;
      this.timeName = timeName;
      this.query.page = 1;
      this.query.search.time = result;
      this.recordData = [];
      this.recordListData();

    },
    
    getiPnoneBottom() { //检测是否为苹果手机
      var userAgent = navigator.userAgent;
      var isiOS = !!userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
      isiOS?this.iPnoneBottomBol = true:this.iPnoneBottomBol = false;
    },
    initData() {
      this.taskShow = false;
      this.query.page = 1;
      this.recordData = [];
      this.awardQuery.page = 1;
      this.awardList = [];
    }
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    
    
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
  
  },
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  async activated() {
    this.initData();
    if(this.$route.query.id || this.$route.query.activityId) {
      this.id = Number(this.$route.query.id);
      this.query.activity_id = Number(this.$route.query.activityId);
      this.getMemberInfo();
      this.awardQuery.activity_id = Number(this.$route.query.activityId);
    }
    if(this.$route.query.clockStatus == 1) {
      this.getMember();
      this.clockListData();
    } else {
      this.getDetail();
    }
    this.clockStatus = this.$route.query.clockStatus;
    this.getiPnoneBottom();
    let yz_basic_info = JSON.parse(localStorage.getItem("yz_basic_info"));
    this.imgPath = yz_basic_info.host;
    let themeColor = yz_basic_info.theme_color || "";
    this.pluginId = yz_basic_info.plugin_setting?.check_in_rebate?.plugin_id;
    this.coThemeColor = this.colorFin(themeColor) || this.colorFin('#F15353');
  }, //如果页面有keep-alive缓存功能，这个函数会触发
}